package com.hzhk.happyrent.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.hzhk.happyrent.App;
import com.hzhk.happyrent.PayInfoBean;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.ZMModel;
import com.hzhk.happyrent.bean.order.OrderInfoModel;
import com.hzhk.happyrent.key.Encryption;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.pay.PayResult;
import com.hzhk.happyrent.ui.activity.order.OrderListActivity;
import com.hzhk.happyrent.ui.view.PredicateLayout;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.glide.ShowImageUtils;
import com.tamic.novate.Throwable;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayPeriodsActivity extends AppCompatActivity {

    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.pay_total)
    TextView payTotal;
    @BindView(R.id.check_wechat_pay)
    ImageView checkWechatPay;
    @BindView(R.id.check_alipay)
    ImageView checkAlipay;


    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
//            Toast.makeText(PayChooseActivity.this, payResult.toString(), Toast.LENGTH_SHORT).show();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                Toast.makeText(PayChooseActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(PayPeriodsActivity.this, ResultPayActivity.class);
                intent.putExtra("rent_total", getIntent().getStringExtra("rent_total"));
                intent.putExtra("come_from", "PayPeriodsActivity");
                startActivity(intent);
                finish();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(PayPeriodsActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_periods);
        App.addDestoryActivity(this,"PayChooseActivity");
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        activityTitlebarCenter.setText("支付");
        payTotal.setText("￥" + getIntent().getStringExtra("pay_total"));
        //rentTotal.setText("总租金  ￥" + getIntent().getStringExtra("pay_total"));
        checkAlipay.setSelected(true);
    }

    @OnClick({R.id.activity_titlebar_left, R.id.rl_wxpay, R.id.rl_alpay, R.id.pay_common})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_titlebar_left:
//                startActivity(new Intent(PayPeriodsActivity.this, OrderListActivity.class));
                finish();
                break;
            case R.id.rl_wxpay:
                if (!checkWechatPay.isSelected()) {
                    checkAlipay.setSelected(false);
                    checkWechatPay.setSelected(true);
                }
                break;
            case R.id.rl_alpay:
                if (!checkAlipay.isSelected()) {
                    checkAlipay.setSelected(true);
                    checkWechatPay.setSelected(false);
                }
                break;
            case R.id.pay_common:
                if ("order_list".equals(getIntent().getStringExtra("come_from"))){
                    getPayId();
                }else if("OrderBuyPayActivity".equals(getIntent().getStringExtra("come_from"))){
                    getPayBuy();
                }else if("OrderReletActivity".equals(getIntent().getStringExtra("come_from"))){
                    payRentRelet();
                }else{
                    getSign();
                }
                break;
        }
    }

    private void payRentRelet() {
        Map<String,Object> params=new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("order_id", getIntent().getStringExtra("order_id"));
        params.put("zu_date", getIntent().getStringExtra("zu_date"));
        params.put("money", getIntent().getStringExtra("pay_total"));
        if (checkWechatPay.isSelected()) {
            params.put("pay_type", "wxpay");
        } else {
            params.put("pay_type", "alipay");
        }
        HttpManager.getInstance().perform_post(API.ORDER_GO_ON, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response,CodeModel.class);
                if(codeModel.getErrCode()==0){
                    if (checkWechatPay.isSelected()) {
                        PayInfoBean zmModel=new Gson().fromJson(response,PayInfoBean.class);
                        weChatPay(zmModel.getData().getWxpaySign());
                    } else {
                        OrderInfoModel zmModel=new Gson().fromJson(response,OrderInfoModel.class);
                        payFor(zmModel.getData().getAlipay_sign());
                    }
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
                Toast.makeText(PayPeriodsActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }

    private void getPayBuy() {
        Map<String,Object> params=new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("order_id", getIntent().getStringExtra("periods_id"));
        if (checkWechatPay.isSelected()) {
            params.put("pay_type", "wxpay");
        } else {
            params.put("pay_type", "alipay");
        }
        HttpManager.getInstance().perform_post(API.BUY_PAY, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response,CodeModel.class);
                if(codeModel.getErrCode()==0){
                    if (checkWechatPay.isSelected()) {
                        PayInfoBean zmModel=new Gson().fromJson(response,PayInfoBean.class);
                        weChatPay(zmModel.getData().getWxpaySign());
                    } else {
                        OrderInfoModel zmModel=new Gson().fromJson(response,OrderInfoModel.class);
                        payFor(zmModel.getData().getAlipay_sign());
                    }
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }

    private void getSign() {
        Map<String,Object> params=new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("periods_id", getIntent().getStringExtra("periods_id"));
        params.put("order_sn", getIntent().getStringExtra("order_sn"));
        if (checkWechatPay.isSelected()) {
            params.put("pay_type", "wxpay");
        } else {
            params.put("pay_type", "alipay");
        }
        HttpManager.getInstance().perform_post(API.PAY_PERIODS, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response,CodeModel.class);
                if(codeModel.getErrCode()==0){
                    if (checkWechatPay.isSelected()) {
                        PayInfoBean zmModel=new Gson().fromJson(response,PayInfoBean.class);
                        weChatPay(zmModel.getData().getWxpaySign());
                    } else {
                        OrderInfoModel zmModel=new Gson().fromJson(response,OrderInfoModel.class);
                        payFor(zmModel.getData().getAlipay_sign());
                    }
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }
    private void getPayId() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("order_id", getIntent().getStringExtra("order_id"));
        if (checkWechatPay.isSelected()) {
            params.put("pay_type", "wxpay");
        } else {
            params.put("pay_type", "alipay");
        }
        HttpManager.getInstance().perform_post(API.ORDER_PAY, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response,CodeModel.class);
                if(codeModel.getErrCode()==0){
                    if (checkWechatPay.isSelected()) {
                        PayInfoBean zmModel=new Gson().fromJson(response,PayInfoBean.class);
                        weChatPay(zmModel.getData().getWxpaySign());
                    } else {
                        OrderInfoModel zmModel=new Gson().fromJson(response,OrderInfoModel.class);
                        payFor(zmModel.getData().getAlipay_sign());
                    }
                }
            }
        });
    }

    private void weChatPay(PayInfoBean.DataBean.WxpaySignBean wxpaySignBean) {
        IWXAPI  api = WXAPIFactory.createWXAPI(App.getContext(), "wx08e1ba509b4f07ea");
        api.registerApp("wx08e1ba509b4f07ea");
        PayReq request = new PayReq();
        request.appId = wxpaySignBean.getAppid();
        request.partnerId = wxpaySignBean.getPartnerid();
        request.prepayId = wxpaySignBean.getPrepayid();
        request.packageValue = wxpaySignBean.getPackageX();
        request.nonceStr = wxpaySignBean.getNoncestr();
        request.timeStamp = Encryption.getTime();
        request.sign = wxpaySignBean.getSign();
        api.sendReq(request);
    }

    private void payFor(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayPeriodsActivity.this);
//                Map<String, String> result = alipay.payV2("alipay_sdk=alipay-sdk-php-20161101&amp;app_id=2017121200620046&amp;biz_content=%7B%22subject%22%3A%22test%22%2C%22out_trade_no%22%3A1516546760%2C%22total_amount%22%3A%220.02%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&amp;charset=UTF-8&amp;format=json&amp;method=alipay.trade.app.pay&amp;sign_type=RSA2&amp;timestamp=2018-01-21+22%3A59%3A20&amp;version=1.0&amp;sign=DkP3DMVHT7%2FDwerBnrjUwJ7ah4a2AeClSEghejXgd9AcNNluhvVIql6Vb0gSCglzykyG2IZ1wTGU8rVpSYdWm9Wra9%2FlyhvlFegu%2FISf489ZNnlfNa0QGcVRtogWIDK82twTqfENtSqD3cV0qfx41JwYvMVxjbvFAa%2FAQeJRR1ebQ7AAWiTeRpkJ7vYOTihw9uEloPqeHpB7VC%2FoYuCqSGyppvJyN6vCX5mEdUaJGEZEelewUHLr9P9R9X0GzVED5JGWvPQPyQyX%2F9c2Tkhs1IpmFrjA7HgVp4yZQolKrfe%2FrAs1T%2BddKSr12MU%2F%2BC9zgylSeafAzs9q1sgNyELYFA%3D%3D",true);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
